package com.Nahida.miHoYoGetGachaLink

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.EditText
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        Toast.makeText(
            this@MainActivity,
            "欢迎使用米哈游抽卡链接获取工具！",
            Toast.LENGTH_SHORT
        ).show()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myWebView: WebView = findViewById(R.id.webview)
        val radioButton1: RadioButton = findViewById(R.id.radioButton1)
        val radioButton2: RadioButton = findViewById(R.id.radioButton2)
        val editText: EditText = findViewById(R.id.input) // 获取EditText引用

        myWebView.settings.javaScriptEnabled = true
        myWebView.settings.domStorageEnabled = true
        myWebView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                // 注入 JavaScript 代码来修改 navigator.language
                view?.evaluateJavascript(
                    """
                            Object.defineProperty(navigator, 'language', {get: function(){return 'zh-CN';}});
                            Object.defineProperty(navigator, 'languages', {get: function(){return ['zh-CN'];}});
                          """, null
                )
            }


            override fun shouldInterceptRequest(
                view: WebView?,
                request: WebResourceRequest?
            ): WebResourceResponse? {
                request?.let {
                    if (radioButton1.isChecked && it.url.toString().contains("public-operation-hk4e.mihoyo.com")) {
                        // 抓取原神请求链接
                        runOnUiThread {
                            Log.d("WebViewRequest", "URL being loaded: ${it.url}")
                            val editText = findViewById<EditText>(R.id.input)
                            editText.setText(it.url.toString())
                            val cm = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                            val clipData = ClipData.newPlainText("", it.url.toString())
                            cm.setPrimaryClip(clipData)
                            Toast.makeText(
                                this@MainActivity,
                                "已复制到剪贴板~",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    } else if (radioButton2.isChecked && it.url.toString().contains("public-operation-hkrpg.mihoyo.com/common/gacha_record/api/getGachaLog")) {
                        // 抓取星铁请求链接
                        runOnUiThread {
                            Log.d("WebViewRequest", "URL being loaded: ${it.url}")
                            val editText = findViewById<EditText>(R.id.input)
                            editText.setText(it.url.toString())
                            val cm = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                            val clipData = ClipData.newPlainText("", it.url.toString())
                            cm.setPrimaryClip(clipData)
                            Toast.makeText(
                                this@MainActivity,
                                "已复制到剪贴板~",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
                return super.shouldInterceptRequest(view, request)
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                url?.let {
                    view?.loadUrl(it)
                }
                return true
            }
        }



        // 设置单选按钮的点击事件
        radioButton1.setOnClickListener {
            editText.setText("")
            Toast.makeText(
                this@MainActivity,
                "开始监听原神抽卡链接，已清空输入框",
                Toast.LENGTH_SHORT
            ).show()
            myWebView.loadUrl("https://ys.mihoyo.com/cloud/#/")
            myWebView.webViewClient = object : WebViewClient() {
                override fun shouldInterceptRequest(
                    view: WebView?,
                    request: WebResourceRequest?
                ): WebResourceResponse? {
                    request?.let {
                        if (it.url.toString().contains("public-operation-hk4e.mihoyo.com")) {
                            // 在主线程中执行 UI 操作
                            runOnUiThread {
                                Log.d("WebViewRequest", "URL being loaded: ${it.url}")
                                val editText = findViewById<EditText>(R.id.input)
                                editText.setText(it.url.toString())
                                val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                                val clipData = ClipData.newPlainText("", it.url.toString())
                                cm.setPrimaryClip(clipData)
                                Toast.makeText(
                                    this@MainActivity,
                                    "链接已复制到剪贴板",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }
                    return super.shouldInterceptRequest(view, request)
                }
            }
        }
        radioButton2.setOnClickListener {
            editText.setText("")
            Toast.makeText(
                this@MainActivity,
                "开始监听星铁抽卡链接，已清空输入框",
                Toast.LENGTH_SHORT
            ).show()
            myWebView.loadUrl("https://sr.mihoyo.com/cloud/#/")
            myWebView.webViewClient = object : WebViewClient() {
                override fun shouldInterceptRequest(
                    view: WebView?,
                    request: WebResourceRequest?
                ): WebResourceResponse? {
                    request?.let {
                        if (it.url.toString().contains("public-operation-hkrpg.mihoyo.com/common/gacha_record/api/getGachaLog")) {
                            // 在主线程中执行 UI 操作
                            runOnUiThread {
                                Log.d("WebViewRequest", "URL being loaded: ${it.url}")
                                val editText = findViewById<EditText>(R.id.input)
                                editText.setText(it.url.toString())
                                val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                                val clipData = ClipData.newPlainText("", it.url.toString())
                                cm.setPrimaryClip(clipData)
                                Toast.makeText(
                                    this@MainActivity,
                                    "链接已复制到剪贴板",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }
                    return super.shouldInterceptRequest(view, request)
                }
            }
        }
    }
}

fun Int.onClick(activity: Activity, click: () -> Unit) {
    activity.findViewById<View>(this).setOnClickListener {
        click()
    }
}

